package com.team01.pokemon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.team01.pokemon.entity.Pokemon;
import com.team01.pokemon.entity.Types;
import com.team01.pokemon.mapper.PokemonMapper;
import com.team01.pokemon.mapper.PokemonTypesMapper;
import com.team01.pokemon.mapper.TypesMapper;
import com.team01.pokemon.result.Result;
import com.team01.pokemon.service.PokemonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team01.pokemon.vo.PokemonVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 宝可梦基础信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-09-13
 */
@Transactional
@Service
public class PokemonServiceImpl extends ServiceImpl<PokemonMapper, Pokemon> implements PokemonService {

    @Autowired
    private PokemonMapper pokemonMapper;

    @Autowired
    private PokemonTypesMapper pokemonTypesMapper;

    @Autowired
    private TypesMapper typesMapper;

    // 属性名映射：英文 -> 中文
    private static final Map<String, String> TYPE_NAME_MAP = new HashMap<>();

    static {
        TYPE_NAME_MAP.put("bug", "虫系");
        TYPE_NAME_MAP.put("dragon", "龙系");
        TYPE_NAME_MAP.put("electric", "电系");
        TYPE_NAME_MAP.put("fairy", "妖精系");
        TYPE_NAME_MAP.put("fighting", "格斗系");
        TYPE_NAME_MAP.put("fire", "火系");
        TYPE_NAME_MAP.put("flying", "飞行系");
        TYPE_NAME_MAP.put("ghost", "幽灵系");
        TYPE_NAME_MAP.put("grass", "草系");
        TYPE_NAME_MAP.put("ground", "地面系");
        TYPE_NAME_MAP.put("ice", "冰系");
        TYPE_NAME_MAP.put("normal", "一般系");
        TYPE_NAME_MAP.put("poison", "毒系");
        TYPE_NAME_MAP.put("psychic", "超能力系");
        TYPE_NAME_MAP.put("rock", "岩石系");
        TYPE_NAME_MAP.put("steel", "钢系");
        TYPE_NAME_MAP.put("water", "水系");
        TYPE_NAME_MAP.put("dark", "恶系");
    }

    /**
     * 转换属性名：英文 -> 中文
     */
    private String convertTypeName(String englishType) {
        if (!StringUtils.hasLength(englishType)) {
            return null;
        }
        return TYPE_NAME_MAP.getOrDefault(englishType.toLowerCase(), englishType);
    }

    /**
     * 为宝可梦列表加载属性信息
     */
    private void loadTypesForPokemons(List<Pokemon> pokemons) {
        if (pokemons == null || pokemons.isEmpty()) {
            return;
        }

        // 获取所有宝可梦ID
        List<Integer> pokemonIds = pokemons.stream()
                .map(Pokemon::getId)
                .collect(Collectors.toList());

        // 查询宝可梦属性关联，比如：pokemon_id=1, type_id=5  (妙蛙种子-草系)
        //创建查询条件
        LambdaQueryWrapper<com.team01.pokemon.entity.PokemonTypes> typesWrapper = new LambdaQueryWrapper<>();
        typesWrapper.in(com.team01.pokemon.entity.PokemonTypes::getPokemonId, pokemonIds);
        List<com.team01.pokemon.entity.PokemonTypes> pokemonTypes = pokemonTypesMapper.selectList(typesWrapper);

        // 查询所有属性信息
        List<Types> allTypes = typesMapper.selectList(null);
        Map<Integer, Types> typeMap = allTypes.stream()
                .collect(Collectors.toMap(Types::getId, type -> type));

        // 为每个宝可梦设置属性信息
        Map<Integer, List<Types>> pokemonTypeMap = pokemonTypes.stream()
                .collect(Collectors.groupingBy(
                        com.team01.pokemon.entity.PokemonTypes::getPokemonId,
                        Collectors.mapping(
                                pt -> typeMap.get(pt.getTypeId()),
                                Collectors.toList())));

        // 设置属性信息
        for (Pokemon pokemon : pokemons) {
            List<Types> types = pokemonTypeMap.getOrDefault(pokemon.getId(), Collections.emptyList());
            pokemon.setTypes(types);
        }
    }

    @Transactional(readOnly = true)
    @Override
    public List<Pokemon> getListByQuery(PokemonVO vo) {
        // 情况一：number or pokemon_name宝可梦名称 进行查询宝可梦列表
        LambdaQueryWrapper<Pokemon> queryWrapper = new LambdaQueryWrapper<>();

        //构建 Pokemon 实体的查询条件。
        if (StringUtils.hasLength(vo.getQuery())) {
            queryWrapper.and(wrapper -> wrapper.eq(Pokemon::getNumber, vo.getQuery())
                    .or()
                    .like(Pokemon::getPokemonName, vo.getQuery()));
        }

        List<Pokemon> list = this.list(queryWrapper);
        // 为结果加载属性信息
        loadTypesForPokemons(list);
        return list;
    }

    @Transactional(readOnly = true)
    @Override
    public List<Pokemon> getListByVO(PokemonVO vo) {
        // 情况二：where category = '种子宝可梦' and (ts.type_name = '草系' or ts.type_name = '毒系')
        // and p.id between 2 and 7
        // 条件一：category分类 进行查询宝可梦列表
        // 条件二：type1 、 type2 属性 进行查询宝可梦列表
        // 条件三：图鉴编号范围 进行查询宝可梦列表

        // 设置默认的编号范围
        if (vo.getBeginNum() == 0) {
            vo.setBeginNum(1);
        }
        if (vo.getEndNum() == 0) {
            vo.setEndNum(pokemonMapper.selectMaxNumber());
        }

        if (StringUtils.hasLength(vo.getType1()) || StringUtils.hasLength(vo.getType2())) {
            // 转换英文属性名为中文属性名
            String type1 = StringUtils.hasLength(vo.getType1()) ? convertTypeName(vo.getType1()) : null;
            String type2 = StringUtils.hasLength(vo.getType2()) ? convertTypeName(vo.getType2()) : null;
            String category = StringUtils.hasLength(vo.getCategory()) ? vo.getCategory() : null;

            List<Pokemon> list;

            // 根据参数情况选择不同的查询方法
            if (type1 != null && type2 != null) {
                // 双属性查询
                list = pokemonMapper.selectByDualType(type1, type2, category, vo.getBeginNum(), vo.getEndNum());
            } else if (type1 != null) {
                // 单属性查询（type1）
                list = pokemonMapper.selectBySingleType(type1, category, vo.getBeginNum(), vo.getEndNum());
            } else {
                // 单属性查询（type2）
                list = pokemonMapper.selectBySingleType(type2, category, vo.getBeginNum(), vo.getEndNum());
            }

            // 为结果加载属性信息
            loadTypesForPokemons(list);
            return list;
        }

        // 构建基础查询条件
        LambdaQueryWrapper<Pokemon> queryWrapper = new LambdaQueryWrapper<>();

        // 分类条件
        if (StringUtils.hasLength(vo.getCategory())) {
            queryWrapper.eq(Pokemon::getCategory, vo.getCategory());
        }

        // 编号范围条件
        queryWrapper.between(Pokemon::getNumber,
                String.format("%03d", vo.getBeginNum()),
                String.format("%03d", vo.getEndNum()));

        List<Pokemon> list = this.list(queryWrapper);
        // 为结果加载属性信息
        loadTypesForPokemons(list);
        return list;
    }

    // 进化页面获取宝可梦列表
    @Transactional(readOnly = true)
    @Override
    public List<Pokemon> getListByVOEvolution(PokemonVO vo) {
        if(!StringUtils.hasLength(vo.getQuery()) && !StringUtils.hasLength(vo.getType1())){
            List<Pokemon> list = this.list();
            return list;
        }


        LambdaQueryWrapper<Pokemon> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.hasLength(vo.getType1())) {
            queryWrapper.and(wrapper -> wrapper.eq(Pokemon::getNumber, vo.getQuery())
                    .or()
                    .like(Pokemon::getPokemonName, vo.getQuery()));
            List<Pokemon> list = this.list(queryWrapper);
            return list;
        }

        List<Pokemon> list = null;
        if(StringUtils.hasLength(vo.getType1())){
            // 单属性查询（type1）
            list = pokemonMapper.selectBySingleType(vo.getType1(), null, 1, 1000);
        }



        // 直接使用前端传来的中文属性名，不需要转换
//        String type1 = StringUtils.hasLength(vo.getType1()) ? vo.getType1() : null;
//        String type2 = StringUtils.hasLength(vo.getType2()) ? vo.getType2() : null;

        // 根据参数情况选择不同的查询方法
//        if (type1 != null && type2 != null) {
//            // 双属性查询
//            list = pokemonMapper.selectByDualType(type1, type2, null, 1, 1000);
//        } else if (type1 != null) {
//            // 单属性查询（type1）
//            list = pokemonMapper.selectBySingleType(type1, null, 1, 1000);
//        } else {
//            // 单属性查询（type2）
//            list = pokemonMapper.selectBySingleType(type2, null, 1, 1000);
//        }

        //loadTypesForPokemons(list);
        return list;
    }

    @Transactional(readOnly = true)
    // @Override
    public List<Pokemon> getPokemonSelectorList() {
        // 查询所有宝可梦的基本信息，按编号排序
        LambdaQueryWrapper<Pokemon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Pokemon::getNumber);
        queryWrapper.select(Pokemon::getId, Pokemon::getNumber, Pokemon::getPokemonName, Pokemon::getImageUrl,
                Pokemon::getEvolutionStage);

        List<Pokemon> list = this.list(queryWrapper);
        return list;
    }

}
